<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { add, update, password } from '../data/api';
import RoleTransfer from './roleTransfer.vue';

import { drawerFormSchema, resetFormSchema, handleId } from '../data/options';
import { message, Tabs, TabPane } from 'ant-design-vue';
import { useThrottleFn } from '@vueuse/core';

const emit = defineEmits(['success']);

const activeKey = ref('1');
const data: any = ref({});
const RoleTransferRef = ref();
const title = computed(() => {
  return `${data.value?.userId ? '编辑' : '新增'}用户`;
});

watch(activeKey, (n) => {
  if (n == '3') {
    setTimeout(() => {
      RoleTransferRef?.value.getData();
    }, 10);
  }
});

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/3',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => onConfirm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      activeKey.value = '1';
      data.value = drawerApi.getData();
      console.log(data.value);
      handleId.value = data.value?.userId;
      formApi.setValues({ ...data.value });
    }
  },
});

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});

// 重置密码表单
const [ResetBaseForm, resetFormApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: resetFormSchema,
  handleSubmit: onResetSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});

//  新增更新提交
async function onSubmit(values: Record<string, any>) {
  console.info('onSubmit');
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  let query = values.roleId ? update : add;
  let res: any = await query({ ...values });
  onSucClose(res.message);
}

//  修改密码提交
async function onResetSubmit(values: Record<string, any>) {
  console.info('onResetSubmit');
  console.log(values);
  const { valid } = await resetFormApi.validate();
  if (!valid) return;
  let query = password;
  let res: any = await query({ ...values });
  onSucClose(res.message);
}

// 修改角色信息提交
const setRoleQuery = async () => {
  let res: any = await RoleTransferRef.value.setRoleQuery();
  console.log(res);
  onSucClose(res.message);
};

//  关闭弹窗
const onSucClose = (messageStr: string) => {
  message.success(messageStr);
  drawerApi.close();
  emit('success');
};

// 提交按钮
const onConfirm = useThrottleFn(async () => {
  if (activeKey.value == '1') {
    formApi.submitForm();
  } else if (activeKey.value == '2') {
    resetFormApi.submitForm();
  } else if (activeKey.value == '3') {
    setRoleQuery();
  }
}, 1000);
</script>
<template>
  <Drawer :title="title">
    <Tabs v-model:activeKey="activeKey">
      <TabPane key="1" tab="用户信息">
        <BaseForm />
      </TabPane>
      <template v-if="data.userId">
        <TabPane key="2" tab="重置密码">
          <ResetBaseForm />
        </TabPane>
        <TabPane key="3" tab="分配角色">
          <RoleTransfer ref="RoleTransferRef" />
        </TabPane>
      </template>
    </Tabs>
  </Drawer>
</template>
